import requestUrl from '../../utils/requestUtil.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //查看下拉图片
    showIndex: 0,
    //种类tab
    cropsTypeAuth: false,
    //种类的id
    skuNo: null,
    //种类选中的索引号
    cropsTabIndex: 0,
    //种类数组
    cropsList: [],
    //日期tab
    dateTabIndex: 0,
    //是否有种植日记
    plantAuth: false,
    //查询种植日记的当前页数
    currentPage: 1,
    //种植日记页数
    pageCount: 1,
    //每次请求的条数
    pages: 4,
    dateProductList: [],
    activeNames: ['0'],
    //是否弹出层
    show: false,
    //照片展示数组
    picList: [],
    //swiper是否有指示点
    indicatorDots: true,
    //swiper是否纵向滑动
    vertical: false,
    //swiper是否自动切换
    autoplay: false,
    //swiper自动切换间隔
    interval: 2000,
    //swiper滑动动画时长
    duration: 500,
    //是否登录
    isLogin: false,
  },
  //日期tab切换
  onDateTabItemTap(e) {
    this.setData({
      dateTabIndex: e.currentTarget.dataset.index
    })
  },
  //种类tab切换
  onCropsTabItemTap(e) {
    this.setData({
      dateProductList:null,
      cropsTabIndex: e.currentTarget.dataset.index,
      skuNo: this.data.cropsList[e.currentTarget.dataset.index].prodNo,
      currentPage: 1
    })
    this.requestPlantDiary(this.data.currentPage);
  },
  // //查看大图
  // showImg(e){
  //   wx.previewImage({
  //     current: e.currentTarget.dataset.imglist[0], // 当前显示图片的http链接
  //     urls: e.currentTarget.dataset.imglist // 需要预览的图片http链接列表
  //   })
  // },
  //展示弹出层,查看大图
  showImg(e) {
    this.setData({
      picList: e.currentTarget.dataset.imglist,
      show: true
    });
  },
  // 关闭弹出层
  onClose() {
    this.setData({
      show: false
    });
  },
  /**
   * 请求种植日记
   */
  requestPlantDiary(page) {

    const userToken = wx.getStorageSync('token');
    let that = this;
    if (page <= that.data.pageCount) {
      requestUrl.requestUrl({
        url: "/app/plant/list",
        params: {
          "limit": that.data.pages,
          "page": page,
          "skuNo": that.data.skuNo
        },
        method: "post",
        header: {
          token: userToken
        }
      }).then((data) => {
        let arr = data.data.list;
        //判断是否是未登录状态
        if (data.data.code == 403 || data.data.msg == "token不能为空") {
          that.setData({
            isLogin: false
          })
        } else {
          //请求第一页
          if (page == 1) {
            //请求数据为空，就将添加种植日记的按钮显示出来
            if (arr.records.length == 0) {
              that.setData({
                plantAuth: false,
                isLogin: true
              })
              return;
            } else {
              let removeList = that.duplicateRemovalList(that.formatDateList(arr.records));
              let list = that.addtoArray(arr.records, removeList);
              that.setData({
                plantAuth: true,
                currentPage: arr.current,
                pageCount: arr.pages,
                dateProductList: list,
                isLogin: true
              })
            }
          } else {
            let list = that.addtoArray(arr.records, that.data.dateProductList);
            that.setData({
              isLogin: true,
              plantAuth: true,
              currentPage: arr.current,
              pageCount: arr.pages,
              dateProductList: list
            })
          }
        }
      }).catch((errorMsg) => {
        console.log("error", errorMsg);
      })
    }

  },
  /**
   * 将数组按照格式转换成另一个数组
   * @param {*} list 
   */
  formatDateList: function (list) {
    var bigArr = [];
    //根据时间变成相应对象，push进bigArr这个数组中去
    list.forEach(item => {
      let date = new Date(item.instTime.replace(/-/g, "/"));
      var year = date.getFullYear();
      let obj = {
        skuNo: item.skuNo,
        date: year,
        diary: []
      }
      bigArr.push(obj)
    });
    return bigArr;
  },
  /**
   * 
   * @param {*} list 需要时间去重的数组
   */
  duplicateRemovalList: function (list) {
    //去除bigArr中时间重复的对象
    var i = 0
    var len = list.length;
    while (i <= len) {
      if (!((i + 1) >= len)) {
        let before = list[i];
        let after = list[i + 1];
        if (before.date == after.date) {
          list.splice(i + 1, 1);
          i = 0;
          len = list.length
        } else {
          i++;
        }
      } else {
        i++;
      }
    }
    return list;
  },
  /**
   * 
   * @param {*} list 需要插入的数组
   * @param {*} bigArr 去重后日期数组
   */
  addtoArray: function (list, bigArr) {
    const weekList = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", ];
    //根据时间，将每条记录push进对应的时间对象里
    list.forEach(item => {
      let date = new Date(item.instTime.replace(/-/g, "/"));
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let week = date.getDay();
      let contextObj = JSON.parse(item.context);
      let contextObj2 = JSON.parse(item.context);
      contextObj2.splice(contextObj2.length - 1, 1);
      const obj = {
        year,
        month,
        day,
        week: weekList[week],
        mode: contextObj[contextObj.length - 1],
        context: contextObj2
      }
      bigArr.forEach(element => {
        if (element.date == year) {
          element.diary.push(obj);
        }
      });
    });
    return bigArr;
  },

  /**
   * 请求产品类型
   */
  requestPlantType() {
    const userToken = wx.getStorageSync('token');
    let that = this;
    requestUrl.requestUrl({
      url: "/app/plant/plant_type",
      method: "get",
      header: {
        token: userToken
      }
    }).then((data) => {
      if (data.data.code == 403 || data.data.msg == "token不能为空") {
        that.setData({
          isLogin: false
        })
      } else {
        if (data.data.list.length == 0) {
          that.setData({
            cropsTypeAuth: false,
            isLogin: true
          })
        } else {
          that.setData({
            cropsTypeAuth: true,
            isLogin: true,
            cropsList: data.data.list,
            skuNo: data.data.list[that.data.cropsTabIndex].prodNo
          })
          this.requestPlantDiary(this.data.currentPage);
        }
      }
    }).catch((errorMsg) => {
      console.log("error", errorMsg);
    })
  },
  //打开隐藏图片、
  panel: function (e) {
    if (e.currentTarget.dataset.index != this.data.showIndex) {
      this.setData({
        showIndex: e.currentTarget.dataset.index
      })
    } else {
      this.setData({
        showIndex: 0
      })
    }
  },

  /**
   * 未登录，跳到登录页
   */
  goLoginPage() {
    wx.navigateTo({
      url: '../login/login',
    })
  },
  /**
   * 无产品信息跳转到添加产品页面
   */
  goToaddCropsInfo() {
    wx.navigateTo({
      url: '../register/register',
    })
  },
  /**
   * 跳转到添加种植日记页面中，并把种类id带过去
   */
  toAddPlanting() {
    wx.navigateTo({
      url: '../planting_details_add/planting_details_add?skuNo=' + this.data.skuNo,
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.requestPlantType();
    // this.requestPlantDiary(this.data.currentPage);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      currentPage: 1
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.requestPlantDiary(this.data.currentPage + 1);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})